package com.boc.langxiang.ui.activity.shop;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.shop.SearchProductContract;
import com.boc.langxiang.entity.bean.ProductsInfo;
import com.boc.langxiang.entity.request.SearchProductRequest;
import com.boc.langxiang.entity.response.ProductListContent;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.presenter.shop.SearchProductPresenter;
import com.boc.langxiang.ui.activity.BaseToolBarActivity;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ProductSearchResultActivity extends BaseToolBarActivity implements BaseQuickAdapter.RequestLoadMoreListener, SearchProductContract.View, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;

    private BaseQuickAdapter<ProductsInfo> mAdapter;
    private String keyWord;
    private String cType;

    private View emptyView;
    private View noMoreView;

    private SearchProductRequest mRequest;
    private SearchProductContract.Presenter mPresenter;

    private int mCurrentPage = 1;

    private boolean mIsLoadMore;
    private boolean mIsOnRefresh;

    private Runnable refreshingRunnable = new Runnable() {
        @Override
        public void run() {
            swipeRefresh.setRefreshing(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_search_result);
        ButterKnife.bind(this);
        keyWord = getIntent().getStringExtra("keyword");
        cType = getIntent().getStringExtra("ctype");

        mRequest = new SearchProductRequest();
        initViews();
    }

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.icon_return_black);
        toolbar.setBackgroundColor(Color.WHITE);
    }

    private void initViews() {
        initAdapter();
        String title = String.format(getResources().getString(R.string.searching_result_title), keyWord);
        getToolbar().setTitle(title);

        swipeRefresh.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        emptyView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);

        noMoreView = getLayoutInflater().inflate(R.layout.view_load_done, recyclerView, false);

        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadMore(mRequest.getPageSize(), true);
        mAdapter.setOnLoadMoreListener(this);

        mAdapter.openLoadAnimation();
        mAdapter.isFirstOnly(true);

        mAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ProductsInfo productsInfo = mAdapter.getData().get(position);
                String designer_status = productsInfo.getDesigner_status();
                switch (designer_status) {
                    case "2":
                        Intent intent = new Intent(mContext, ProductDetailActivity.class);
                        intent.putExtra("id", productsInfo.getId());
                        mContext.startActivity(intent);
                        break;
                    case "3":
                        intent = new Intent(mContext, ProductDetail2Activity.class);
                        intent.putExtra("id", productsInfo.getId());
                        mContext.startActivity(intent);
                        break;
                }
            }
        });

        recyclerView.setAdapter(mAdapter);

        swipeRefresh.setOnRefreshListener(this);


        initData();

    }

    private void initData() {
        mPresenter = new SearchProductPresenter(this);
        mRequest.setCtype(cType);
        mRequest.setKeyword(keyWord);
        onRefresh();
    }

    private void initAdapter() {
        mAdapter = new BaseQuickAdapter<ProductsInfo>(R.layout.product_all_item, new ArrayList<ProductsInfo>()) {
            @Override
            protected void convert(BaseViewHolder helper, ProductsInfo item) {
                helper.setText(R.id.product_title_tv, item.getTitle());
                helper.setText(R.id.price_tv, "￥" + item.getPrice());

                PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhoto().get(0).getUrl()
                        , (ImageView) helper.getView(R.id.img_iv));
            }
        };
    }

    @Override
    public void onLoadMoreRequested() {
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                if (mIsLoadMore || mIsOnRefresh) {
                    mAdapter.notifyDataChangedAfterLoadMore(true);
                    return;
                }
                mIsLoadMore = true;
                int page = mCurrentPage + 1;
                mRequest.setPage(page);
                mPresenter.loadMore(mRequest);
            }
        });

    }

    @Override
    public void onRefreshSuccess(ProductListContent content) {
        mIsOnRefresh = false;
        if (content.getRes() != null) {
            if (content.getRes().size() > 0) {
                mAdapter.setNewData(content.getRes());
                if (content.getRes().size() < mRequest.getPageSize()) {
                    mAdapter.addFooterView(noMoreView);
                    mAdapter.notifyDataChangedAfterLoadMore(false);
                }
            }
        }
    }

    @Override
    public void onLoadMoreSuccess(ProductListContent content) {
        mIsLoadMore = false;
        if (content.getRes() != null && content.getRes().size() > 0) {
            mCurrentPage = mRequest.getPage();
            if (content.getRes().size() < mRequest.getPageSize()) {
                mAdapter.addFooterView(noMoreView);
                mAdapter.notifyDataChangedAfterLoadMore(content.getRes(), false);
            } else {
                mAdapter.notifyDataChangedAfterLoadMore(content.getRes(), true);
            }
        } else {
            mAdapter.addFooterView(noMoreView);
            mAdapter.notifyDataChangedAfterLoadMore(false);
        }
    }

    @Override
    public void showLoading() {
        swipeRefresh.post(refreshingRunnable);
    }

    @Override
    public void hideLoading() {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(false);
            }
        });
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(this, msg);
    }

    @Override
    public void onRefresh() {
        if (mIsLoadMore || mIsOnRefresh) {
            hideLoading();
            return;
        }
        mIsOnRefresh = true;
        mCurrentPage = 1;
        mRequest.setPage(1);
        mPresenter.refresh(mRequest);
    }
}
